<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="../../plugins/layui/css/layui.css">  
    <link rel="stylesheet" href="../../plugins/font-awesome/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="../../plugins/datatables/css/jquery.dataTables.css">          
    <link rel="stylesheet" href="../../css/rmp.css">
</head>
<body>
<div class="layui-fluid">
    <blockquote class="layui-elem-quote layui-quote-nm rmp-monitoring-btn-tools">
        <button class="layui-btn">列显示</button>
        <button class="layui-btn">视图显示</button>
        <button class="layui-btn">批量操作</button>
        <button class="layui-btn" style="float: right;"><i class="fa fa-bell"></i></button>
        <button class="layui-btn" style="float: right;">视图控制</button>
    </blockquote>
    <div class="rmp-monitoring-content">
        <div class="layui-collapse">

        </div>
    </div>
</div>

<script src="../../plugins/jquery.js"></script>
<script src="../../plugins/layui/layui.js"></script>
<script src="../../plugins/datatables/js/jquery.dataTables.js"></script>
<script src="../../plugins/Echarts/echarts.min.js"></script>
<script src="../../plugins/Echarts/shine.js"></script>
<script src="../../js/global.js"></script>
<script>
    //加载loading  index
    var globalLoadIndex;
    //不同类型的DT实例和相关运行参数存放
    var viewInstances = {};
    //视图显示设置
    var viewVisibleSetting = {};
    //全部数据内容
    var infoData;
    //本地计数器
    var infoCount;
    //预警信息
    var alertInfo = [];
    
    var isExecCommand = false;

    //后台任务，比如数据量检测，预警检测等
    var taskIds = {
        checkInfoCount:null,
        checkAlertValue:null,
        playAlertAnnouncement:null
    };

    layui.use(['layer', 'element', 'form', 'util', 'rmpmultipleselect', 'table'], function(){
        var layer = layui.layer,
                element = layui.element,
                form = layui.form,
                util = layui.util,
                rmpmultipleselect = layui.rmpmultipleselect,
                table = layui.table;

        /*************************************初始化****************************************************************/
        //刷新关闭页面保存设置
        window.onbeforeunload = function() {
            saveLocalSetting();
        }

        //初始化视图面板区域
        $(".rmp-monitoring-content > .layui-collapse").append(templates["monitoring-content-table-tpl"]);
        element.render('collapse');

        //初始化工具条插件
        util.fixbar();

        //初始化本地设置
        initLocalSetting();

        //初始化相关模板/页面
        var columnViewHtml = templates["monitoring-column-view-tpl"];
        var typeViewTpl = templates["monitoring-type-view-tpl"];
        var viewControlUtilHtml = templates["monitoring-view-control-util-tpl"];
        var alertInfoViewTpl = templates["monitoring-alert-info-view-tpl"];

        //初始化所有Datatables
        initDatatables();

        //开启后台任务
        //检测最大缓存数据量
        taskIds.checkInfoCount = setInterval(checkInfoCount, userSetting.monitoring.cacheDataDetectionIntervalTime);
        //检测预警信息
        taskIds.checkAlertValue = setInterval(checkAlertValue, userSetting.monitoring.alertMonitorIntervalTime);
        //播放公告
        taskIds.playAlertAnnouncement = setInterval(playAlertAnnouncement, userSetting.monitoring.playNoticIntervalTime);

        /********************************************jquery代理事件监听******************************************************************************/
        $(document).delegates({
            //列显示设置
            'blockquote > button:eq(0)':function(){
                layer_show('列显示设置', columnViewHtml, 800, 400, 1, function(layero, index){
                    layero.find('input').each(function(i, n){
                        viewInstances[$(n).attr('server-type')]['columnVisible'][$(n).attr('data-column')] && $(n).attr("checked",true);
                    });
                    form.render('checkbox');
                    $('#rmp-monitoring-column-view-btns > button:eq(0)').click();
                })
            },
            //视图显示设置
            'blockquote > button:eq(1)':function(){
                layer_show('视图显示设置', typeViewTpl.render(viewVisibleSetting), 600, 200, 1, function(layero, index){
                    form.render('checkbox');
                })
            },
            //批量操作
            'blockquote > button:eq(2)':function(){
                var checkdata =  $("td > input:checked");
                if (checkdata.length < 1) {
                    return false;
                }

                layer.confirm('请点击下方按钮选择操作:', {shadeClose:true, title:'批量操作', btn: ['取消', '批量删除', '批量重连'],
                            btn3:function(index, layero){//批量重连
                                layer.confirm('确认重连选中的' + checkdata.length + '条记录?', {title:'警告'}, function(index1){
                                    batchComplexOp(function(opCount){
                                        checkdata.each(function(i, n){
                                            serverReconnect(n, function(json){
                                                if (json.returnCode == 0) {
                                                    opCount.success += 1;
                                                } else {
                                                    opCount.fail += 1;
                                                }
                                                opCount.total += 1;
                                            }, true);
                                        });
                                    }, checkdata.length);


                                    layer.close(index1);
                                });

                                layer.close(index);
                            }}
                        , function(index, layero) {
                            layer.close(index);
                        }
                        , function(index, layero) { //批量删除
                            layer.confirm('确认删除选中的' + checkdata.length + '条记录?', {title:'警告'}, function(index1){
                                batchComplexOp(function(opCount){
                                    checkdata.each(function(i, n){
                                        serverDel(n, function(json){
                                            if (json.returnCode == 0) {
                                                opCount.success += 1;
                                                viewInstances[$(n).attr('server-type')]['table'].row($(n).parents('tr')).remove().draw();
                                            } else {
                                                opCount.fail += 1;
                                            }
                                            opCount.total += 1;
                                        }, true);
                                    });
                                }, checkdata.length);

                                layer.close(index1);
                            });
                            layer.close(index);
                        });
            },
            //打开视图控制工具条
            'blockquote > button:eq(4)':function(){
                layer_show('视图控制工具', viewControlUtilHtml, 900, 400, 1, function(layero, index) {
                    window.multipleSelectObj = rmpmultipleselect({
                        ele:layero.find('select'),
                        width:300,
                    });
                }, null, function(){
                    delete window.multipleSelectObj;
                });
            },
            //视图控制工具：停止刷新
            '#view-control-util-page button:eq(0)':function(){
                var types = multipleSelectObj.selected.selectedValue;
                if (types.length < 1) return false;

                $.each(types, function(i, n){
                    refreshControl(n, 'stop');
                    $("#view-control-util-page #tips").append('<p><strong>' + n + '</strong>类型图表已停止刷新.</p>');
                });

            },
            //视图控制工具：开始刷新
            '#view-control-util-page button:eq(1)':function(){
                var types = multipleSelectObj.selected.selectedValue;
                if (types.length < 1) return false;

                $.each(types, function(i, n){
                    refreshControl(n, 'start');
                    $("#view-control-util-page #tips").append('<p><strong>' + n + '</strong>类型图表已开始刷新.</p>');
                });
            },
            //视图控制工具：清除缓存
            '#view-control-util-page button:eq(2)':function(){
                var types = multipleSelectObj.selected.selectedValue;
                if (types.length < 1) return false;

                $.each(types, function(i, n){
                    delData(n);
                    $("#view-control-util-page #tips").append('<p>已清除<strong>' + n + '</strong>类型图表缓存.</p>');
                });
            },
            //视图控制工具：下载数据
            '#view-control-util-page button:eq(3)':function(){
                var types = multipleSelectObj.selected.selectedValue;
                if (types.length < 1) return false;

                saveData(types, function(json) {
                    validatReturnJson(json, function(){
                        $("#view-control-util-page #tips").append('<p>已保存<strong>' + types.join(',') + '</strong>类型数据,<a href="../../' + json.data + '" target="_blank">请右键另存为下载</a>.</p>');
                    })
                })


            },
          	//视图控制工具：删除某个表格的所有监控信息
            '#view-control-util-page button:eq(4)':function(){
                var types = multipleSelectObj.selected.selectedValue;
                if (types.length < 1) return false;

                delTableData(types, function(json, type) {
                    validatReturnJson(json, function(){
                    	(viewInstances[type]['table']).clear();
                        $("#view-control-util-page #tips").append('<p>已删除<strong>' + type + '</strong>表格数据.</p>');
                    })
                });
            },
            //预警信息查看
            'blockquote > button:eq(3)':function(){
                if ($('.layui-layer-content > #rmp-monitoring-alert-info-table').length > 0) {
                    return false;
                };
                layer_show('预警信息查看', alertInfoViewTpl.render(alertInfo), 1100, 550, 1, null, null, null, {
                    shade:false
                });
            },
            //动态数据通过echarts图表显示
            '.dynamic-data':function(){
                showEchartsView(this);
            },
            //列显示checkbox控制开关
            '#rmp-monitoring-column-view-btns > button':function(){
                var serverType = $(this).attr('server-type');
                var $views = $(this).parents('.layer-show-view').find('span[server-type="' + serverType + '"]');
                $views.siblings('span').hide();
                $views.show();
                $(this).removeClass('layui-btn-primary').siblings('button').addClass('layui-btn-primary');
            },
            //删除服务器
            '.rpm-monitoring-btn-del':function() {
                var that = this;
                layer.confirm('确定删除该服务器？', {title:'警告'}, function(index) {
                    serverDel(that);
                    layer.close(index);
                });

            },
            //重连服务器
            '.rpm-monitoring-btn-reconnect':function() {
                var that = this;
                layer.confirm('确定重新连接该服务器？', {title:'警告'}, function(index) {
                	globalLoadIndex = layer.msg('正在重新连接服务器...', {icon:16, time:9999999, shade:0.4});
                    serverReconnect(that, function() {
                    	layer.close(globalLoadIndex);
                    });
                    layer.close(index);
                });
            },
            //weblogic/tomcat打开jvm监控
            '.rpm-monitoring-btn-other-jvm':function() {
            	var serverType = $(this).attr('server-type');
            	var viewId = $(this).attr('data-id');
            	globalLoadIndex = layer.msg('正在尝试启动监控...', {icon:16, time:9999999, shade:0.4});
            	$.post(serverInfos['jvm']['namespace'] + MONITORING_SERVER_ADD_JVM_URL, {userKey:userKey, serverType:serverType, viewId:viewId}, function(json) {
            		layer.close(globalLoadIndex);
            		validatReturnJson(json, function(){
            			layer.msg('成功开启监控!', {icon:1, time:1500});
                    })
            	});
            },
            //linux设置jvm监控
            '.rpm-monitoring-btn-linux-jvm':function() {
            	var serverType = $(this).attr('server-type');
            	var viewId = $(this).attr('data-id');
            	globalLoadIndex = layer.msg('正在加载中...', {icon:16, time:9999999, shade:0.4});
            	$.post(serverInfos['linux']['namespace'] + MONITORING_SERVER_CHECK_LINUX_JPS_URL,
            			{userKey:userKey, serverType:serverType, viewId:viewId}, function(json) {
            				layer.close(globalLoadIndex);
            				validatReturnJson(json, function(){
            					layer_show('检查java进程', templates['rmp-monitoring-linux-jvm'].render(json.data), 800, 430, 1);
                    			layer.msg('加载成功!', {icon:1, time:1500});
                            })
            			});
            },
            //linux上的java进程查看
            '#rmp-monitoring-linux-check-jps':function() {
            	var $jpsForm = $("#linux-jps-form");            	
            	var javaHome = $jpsForm.find('#javaHome').val();
            	var viewId = $jpsForm.find('#viewId').val();           	
            	globalLoadIndex = layer.msg('查询中...', {icon:16, time:9999999, shade:0.4});
           		$.post(serverInfos['linux']['namespace'] + MONITORING_SERVER_CHECK_LINUX_JPS_URL,
		       			{userKey:userKey, javaHome:javaHome, viewId:viewId}, function(json) {
		       				layer.close(globalLoadIndex);
		       				validatReturnJson(json, function(){
		       					$jpsForm.find('#javaHome').val(json.data.javaHome);
		       					$jpsForm.find('#processes').val(json.data.processes);
		               			layer.msg('加载成功!', {icon:1, time:1500});
		                       })
		       			});          	
            },
            //开启linux上的jvm-gc监控
            '#rmp-monitoring-linux-add-jvm':function() {
            	var $jpsForm = $("#linux-jps-form");  
            	
            	var pid = $jpsForm.find('#pid').val();
            	
            	if (!(/^[0-9]+$/.test(pid))) {
            		layer.msg('pid设置不正确!', {icon:5, time:1500});
            		return;
            	}
            	
            	var viewId = $jpsForm.find('#viewId').val(); 
            	var processName = $jpsForm.find('#processName').val();
            	globalLoadIndex = layer.msg('正在尝试启动监控...', {icon:16, time:9999999, shade:0.4});
            	$.post(serverInfos['jvm']['namespace'] + MONITORING_SERVER_ADD_JVM_URL
            			, {userKey:userKey, serverType:'linux', viewId:viewId, pid:pid, processName:processName}, function(json) {
            					layer.close(globalLoadIndex);
			            		validatReturnJson(json, function(){
			            			layer.msg('成功开启监控!', {icon:1, time:1500});
			                    })
            	});
            },
            //命令执行控制台
            ".rmp-monitoring-console":function(){
            	var serverType = $(this).parents('.layui-colla-item').attr('id');         	
            	
            	if (!viewInstances[serverType]['table'].data().any()) {
            		layer.msg('当前无' + serverType + '类型的监控服务器!', {icon:5, time:1600});
            		return false;
            	}
            	layer_show(serverType + "-Console控制台", templates['rmp-monitoring-server-console'].render({infoData:infoData[serverType], serverType:serverType}), 800, 560, 1, function(layero, index){
            		 window.multipleSelectObj = rmpmultipleselect({
                         ele:layero.find('select'),
                         width:300,
                     });
            		//回车键执行命令       					
					 layero.keyup(function (event) {
						 var keycode = event.which;
						 if(keycode == 13){
							 $('#rmp-console-send-command-btn').click();
						 }
					 });
            	}, null, function() {
            		isExecCommand = false;
            		delete window.multipleSelectObj;
            		showWaitFor($("#rmp-console-command-tips"), false);
            	});
            },
            //发送执行命令
            '#rmp-console-send-command-btn':function() {
            	if (isExecCommand) {
            		layer.msg('当前正在执行命令,请等待执行完成!', {time:1600});
            		return;
            	}
            	
            	var viewIds = window.multipleSelectObj.selected.selectedValue;
            	if (viewIds.length == 0) {
            		layer.msg('请至少选择一个执行服务器!', {icon:5, time:1600});
            		return;
            	}
            	var command = $("#rmp-console-command").val();
            	if (command == null || command == "") {
            		layer.msg('请输入执行命令!', {icon:5, time:1600});
            		return;
            	}           	
            	showWaitFor($("#rmp-console-command-tips"), true);
            	isExecCommand = true;
            	
            	//生成execTag
            	var tag = uuid();
            	$("#rmp-console-command-tag").val(tag);
            	$.post(serverInfos[$("#rmp-console-server-type").val()]['namespace'] + MONITORING_SERVER_SEND_COMMAND_URL, {userKey:userKey, viewIds:viewIds.join(','), command:command, tag:tag}, function(json) {
            		showWaitFor($("#rmp-console-command-tips"), false);
            		isExecCommand = false;
            		validatReturnJson(json, function() {
            			if (json.data == null) {
            				return;
            			}
            			
            			if (json.data.length == 1) {
            				$("#rmp-console-renturn-info").val(json['data'][0].returnInfo);
                			$("#rmp-console-command-tips").text('执行耗时:' + json['data'][0].useTime + 'ms');
                			return;
            			}  
            			var returnInfo = '';
            			$.each(json.data, function(i, n){
            				returnInfo += n.host + '\n\n' + n.returnInfo + '\n' + '执行耗时：' + n.useTime;
            				returnInfo += '\n------------------------------------------------------------------------------------------------------------------\n';
            			});
            			$("#rmp-console-renturn-info").val(returnInfo);
            			$("#rmp-console-command-tips").text('');
            		});
            	});
            	
            	
            },
            //中断命令执行
            '#rmp-console-break-command-btn':function() {
            	var tag = $("#rmp-console-command-tag").val();
            	if (tag != null && tag.length > 0) {
            		$.post(serverInfos[$("#rmp-console-server-type").val()]['namespace'] + MONITORING_SERVER_BREAK_COMMAND_URL, {userKey:userKey, tag:tag}, function(json) {               		
                		validatReturnJson(json, function() {
                			layer.msg('已发送中断执行请求,请稍等待!', {icon:1, time:1500});
                			$("#rmp-console-command-tag").val('');								               			
                		});
                	});
            	}
            },
            //查看jvm堆栈信息
            '.rmp-monitoring-jvm-stack':function() {
            	var viewId = $(this).attr('data-id');
            	globalLoadIndex = layer.msg('正在获取堆栈信息...', {icon:16, time:9999999, shade:0.4});
            	$.post(serverInfos['jvm']['namespace'] + MONITORING_SERVER_SHOW_STACK_INFO_URL, {userKey:userKey, viewId:viewId}, function(json) {
          			layer.close(globalLoadIndex);
            		validatReturnJson(json, function(){
            			layer.prompt({
          				  formType: 2,
          				  value: json.data,
          				  title: '实时堆栈信息查看',
          				  maxlength:999999,
          				  area: ['800px', '350px'] //自定义文本域宽高
          				}, function(value, index, elem){
          				  layer.close(index);
          				});
                    })
          		});
            }
        });
        /********************************************layui form 事件监听******************************************************************************/
        //列显示控制
        form.on('checkbox(rmp-column-view)', function(data){
            var $obj = $(data.elem);
            viewInstances[$obj.attr('server-type')]['columnVisible'][$obj.attr('data-column')] = data.elem.checked;
            (viewInstances[$obj.attr('server-type')]['table']).column($obj.attr('data-column')).visible(data.elem.checked);

        });

        //视图显示控制
        form.on('checkbox(rmp-type-view)', function(data){
            var $obj = $(data.elem);
            var serverType = $obj.attr('server-type');
            viewVisibleSetting[serverType] = data.elem.checked;
            if (data.elem.checked) {
                $("#" + serverType).show();
                //表格重绘防止列宽显示异常
                (viewInstances[serverType]['table']).draw();
                refreshControl(serverType, 'start');
            } else {
                $("#" + serverType).hide();
                refreshControl(serverType, 'stop');
            }
        });


        /********************************************公用方法**************************************************************************************/
        //datable初始化公共方法
        function initDatatables () {
            var initCount = 0;
            globalLoadIndex = layer.msg('正在初始化...', {icon:16, time:999999, shade:0.4});
            $.each(serverInfos.viewTypes, function(type, name){
                viewInstances[type] = {};
                var table = $('#' + type + ' .layui-table').on('xhr.dt', function(e, settings, json, xhr) {
                    //在ajax失败或者请求不成功时的处理
                    if (xhr.status != 200) {
                        $.each($("#" + type + " ." + SERVER_CONNECT_STATUS_CLASS), function (i, n) {
                            $(n).hasClass("layui-bg-green") && $(n).removeClass("layui-bg-green");
                            $(n).text("网络中断");
                        });
                    }
                    if (json && json.returnCode != 0) {
                    	$.each($("#" + type + " ." + SERVER_CONNECT_STATUS_CLASS), function (i, n) {
                            $(n).hasClass("layui-bg-green") && $(n).removeClass("layui-bg-green");
                            $(n).text("请求失败!");
                        });
                    }
                }).DataTable($.extend(true, {}, DT_CONSTANT.DATA_TABLES.DEFAULT_OPTION,{
                    initComplete:function(settings, json){
                        //全选按钮
                        $(table.table().container()).find("th > input[type='checkbox']:eq(0)").click(function() {
                            if ($(this).is(":checked")) {
                                $(table.table().container()).find("td > input[type='checkbox']").prop("checked", true);
                            } else {
                                $(table.table().container()).find("td > input[type='checkbox']").prop("checked", false);
                            }
                        });
                        //列显示
                        viewInstances[type]['columnVisible'] = {};
                        $.each(serverInfos[type]['tableColumn'], function(index, name){
                            viewInstances[type]['columnVisible'][index + ''] =
                                    table.column(index).visible() ? true : false;

                        });

                        //开启定时刷新,
                        refreshControl(type, 'start');

                        //关闭load
                        initCount++;
                        if (initCount == rmputils.jsonUtils.len(serverInfos.viewTypes)) {
                            layer.close(globalLoadIndex);
                        }
                    }
                }, serverInfos[type]['dtInitParameter']));
                viewInstances[type]['table'] = table;
            });
        }

        /**
         * 控制表格刷新
         * @param type 类型
         * @param mode 操作  start|stop
         */
        function refreshControl(type, mode) {
            var intervalId = viewInstances[type]['intervalId'];
            if (mode == 'start') {
                //只有显示的和当前没有再刷新状态的表格才能开启定时刷新
                if (viewVisibleSetting[type] && (intervalId == undefined || intervalId == 0)) {
                    viewInstances[type]['intervalId'] = setInterval(function(){
                        refreshInfoData(type);
                    }, userSetting.monitoring.refreshIntervalTime);
                }
                $("#" + type + " .layui-anim").addClass("layui-anim-rotate");
            }

            if (mode == 'stop') {
                //在开启刷新状态时才能停止
                clearInterval(intervalId);
                viewInstances[type]['intervalId'] = 0;
                $("#" + type + " .layui-anim").removeClass("layui-anim-rotate");
            }

        }

        /**
         * 表格定时获取数据并刷新
         */
        function refreshInfoData(serverType) {

            var table = viewInstances[serverType]['table'];
            if (table == null) return false;

            table.ajax.reload(function(json){
                //保存数据到infoData
                $.each(json.data, function(i, info){
 
                    infoCount++;
                    //初始化
                    infoData[serverType] == null && (infoData[serverType] = {});
                    if (infoData[serverType][info.viewId] == null) {
                        infoData[serverType][info.viewId] = $.extend(true, {}, serverInfos[serverType]['propertyObject']);
                        infoData[serverType][info.viewId]['time'] = [];
                        infoData[serverType][info.viewId]['host'] = (info.realHost != null && info.realHost.length > 0 ? info.realHost  : info.host) + ':' + info.port;
                        infoData[serverType][info.viewId]['tags'] = info.tags;
                    }
                    var thisData = infoData[serverType][info.viewId];
                    //保存数据
                    $.each(info.info, function(itemName, value) {

                        if (itemName == 'time') {
                            thisData['time'].push(value);
                            return true;
                        }

                        if (typeof value == 'object') {
                            $.each(value, function(itemName2, value2) {
                                //第三层
                                if (typeof value2 == 'object') {
                                    //第三层主要针对weblogic中不同jdbc数据源信息
                                    $.each(value2, function(itemName3, value3) {
                                        //itemName=jdbcInfo  itemName3=属性   itemName2=数据源名称
                                        thisData[itemName][itemName3][itemName2] == null && (thisData[itemName][itemName3][itemName2] = []);
                                        thisData[itemName][itemName3][itemName2].push(value3);
                                    });
                                } else {
                                	thisData[itemName][itemName2] != null && thisData[itemName][itemName2].push(value2);
                                }
                            });
                        } else {
                        	thisData['commonInfo'][itemName] != null && thisData['commonInfo'][itemName].push(value);
                        }
                    });

                });
            });

        }



        /**
         * 展示echarts图表
         * @param elem 触发按钮节点
         */
        function showEchartsView(elem) {

            //获取节点上绑定的元素信息
            var serverType = $(elem).attr('server-type'); //weblogic
            var itemName = $(elem).attr('data-item');//jdbcInfo
            var dataName = $(elem).attr('data-name');//availableConnectionCount
            var dataId = $(elem).attr('data-id');//viewId

            //判断该指定类目是否已经有展示图表了
            /*            if ($("#" + serverType + "-" + itemName + "-" + dataName + "-" + dataId)) {
             return false;
             }*/

            //组装echarts配置数据
            var title = serverInfos[serverType]['constant'][dataName];
            var seriesData = infoData[serverType][dataId][itemName][dataName];
            var times = infoData[serverType][dataId]['time'];

            //是否为多类目折线图
            var mode = rmputils.arrayUtils.isArray(seriesData) ? false : true;

            var option = {};

            //标题,多类目折线图不需要标题
            if (!mode) {
                option.title = {
                    text: title,
                    x: 'center',
                    align: 'right',
                    top:'top',
                    textStyle:{
                        color:'#EF2203'
                    }
                };
            }

            //提示框触发类型
            option.tooltip = {
                trigger: 'axis'
            };

            //工具组件
            option.toolbox = {
                show: true,
                feature: {
                    dataView: {readOnly: true}, //数据视图
                    saveAsImage:{},// 保存为图片
                    dataZoom:{}
                }
            };

            //x轴定义
            option.xAxis = {
                type : 'category',
                boundaryGap: false,
                data : times,
                axisLine: {onZero: false}
            };

            //var YType = "value";

            /*            if(!mode && rmputils.numberUtils.isNum(seriesData[0])){
             //y轴定义
             option.yAxis = {
             type : "category",// Y轴的定义
             axisLine: {onZero: false},
             boundaryGap: false
             };
             }*/

            //y轴定义
            option.yAxis = {
                type : "value",// Y轴的定义
                max:'dataMax',
                boundaryGap: [0.1, 0.1],
                axisLabel: {
                	formatter: function (value, index) {
                		if (String(value).indexOf('.') != -1) {
                			return value.toFixed(2);
                		}
                		return value;
                	} 
                }
            };

            //多类目折线图 图例组件
            if (mode) {
                option.legend = {
                    data:[]
                };
                $.each(seriesData, function(i, n) {
                    option.legend.data.push(i);
                });
            }

            //数据
            option.series = [];

            if (mode) {
                $.each(seriesData, function(i, n) {
                    option.series.push({
                        name:i,
                        type:'line',
                        smooth:true,
                        data:n
                    });
                });
            } else {
                option.series.push({
                    name:title,
                    type:'line',
                    smooth:true,
                    data: seriesData
                })
            }

            //显示页面层图表,同一个页面可显示多个视图
            var thisEcharts;
            var idOfInterval;
            layer_show(title, '<div class="rmp-monitoring-echarts-view" id="' + serverType + "-" + itemName + "-" + dataName + "-" + dataId + '"></div>',
                    880, 460, 1, function(){
                        thisEcharts = echarts.init(document.getElementById(serverType + "-" + itemName + "-" + dataName + "-" + dataId), 'shine');
                        thisEcharts.setOption(option);
                        idOfInterval = setInterval(function () {
                            thisEcharts.setOption(option);
                        }, userSetting.monitoring.refreshIntervalTime);
                    }, null, function(){
                        clearInterval(idOfInterval);
                    });
        }

        /*******************************************************************后台任务*************************************************************************/

        /**
         *
         * 检查缓存中的最大数据量并进行处理
         *
         */
        function checkInfoCount() {
            if (infoCount >= Number(userSetting.monitoring.maxInfoDataCount)) {
                //需要自动清理
                if (rmputils.stringUtils.toBoolean(userSetting.monitoring.autoClearDataFlag)) {
                    //是否需要自动保存
                    if (rmputils.stringUtils.toBoolean(userSetting.monitoring.autoSaveDataFlag)) {
                        saveData('all');
                    }
                    //自动清理
                    delData('all');
                    message.show({msg:'当前缓存中的数据量已超过设置的最大值[' + userSetting.monitoring.maxInfoDataCount + '],系统已进行自动清除处理!(如不想进行自动清理请在"配置选项"中关闭此选项)',
                        autoClose:true, time:3000});
                } else {
                    message.show({msg:'当前缓存中的数据量已超过设置的最大值[' + userSetting.monitoring.maxInfoDataCount + '],请手动进行数据清除!)',
                        skin:'red', autoClose:true});
                }

            }
        }

        /**
         *
         * 检查预警值
         *
         */
        function checkAlertValue() {
            alertInfo.length = 0;
            $.each(infoData, function(type, infos){
                $.each(infos, function(viewId, firstInfo){
                    $.each(firstInfo, function(itemName1, info){
                        if (typeof info == 'object') {
                            $.each(info, function(itemName, dataArr) {
                                if (serverInfos[type]['alertSettingValue'][itemName] != undefined) {
                                    var mode = serverInfos[type]['alertSettingValue'][itemName]['mode'];
                                    var sign = serverInfos[type]['alertSettingValue'][itemName]['sign'];
                                    var alertValue = userSetting['alert'][type][itemName];
                                    var time = firstInfo.time[firstInfo.time.length -1];
                                    if (rmputils.arrayUtils.isArray(dataArr)) {
                                        var currentValue = dataArr[dataArr.length - 1];
                                        if (eval(currentValue + mode + alertValue)) {
                                            alertInfo.push({
                                                viewId:viewId,
                                                host:firstInfo.host,
                                                time:time,
                                                serverType:type,
                                                tags:firstInfo.tags,
                                                itemName:serverInfos[type]['constant'][itemName].replace(/(\[.*\])/,''),
                                                itemName2:'',
                                                currentValue:currentValue + sign,
                                                alertValue:alertValue + sign
                                            });
                                        }
                                    } else {
                                        $.each(dataArr, function(itemName2, dataArr2){
                                            var currentValue = dataArr2[dataArr2.length - 1];
                                            if (eval(currentValue + mode + alertValue)) {
                                                alertInfo.push({
                                                    viewId:viewId,
                                                    host:firstInfo.host,
                                                    time:time,
                                                    serverType:type,
                                                    tags:firstInfo.tags,
                                                    itemName:serverInfos[type]['constant'][itemName].replace(/(\[.*\])/,''),
                                                    itemName2:itemName2,
                                                    currentValue:currentValue + sign,
                                                    alertValue:alertValue + sign
                                                });
                                            }
                                        });
                                    }
                                };
                            });
                        }
                    });
                });
            });

            $('blockquote > button:eq(3) > span').remove();
            if (alertInfo.length > 0) {
                $('blockquote > button:eq(3)').append('<span class="layui-badge">' + alertInfo.length + '</span>');
            }
            if ($('.layui-layer-content > #rmp-monitoring-alert-info-table').length > 0) {
                $('#rmp-monitoring-alert-info-table').parent('.layui-layer-content').html(alertInfoViewTpl.render(alertInfo));
            }
        }

        /**
         *
         * 播放预警公告信息
         *
         */
        function playAlertAnnouncement() {
            if (!rmputils.stringUtils.toBoolean(userSetting.other.alertInfoTipShow)) return false;

            if (alertInfo.length == 0) {
                window.alertIndex = 0;
                return false;
            }
            (window.alertIndex == undefined || window.alertIndex > alertInfo.length - 1) && (window.alertIndex = 0);
            var currentAlertInfo = alertInfo[window.alertIndex];
            message.show({
                msg:serverInfos.viewTypes[currentAlertInfo.serverType] + '服务器 ' + currentAlertInfo.host + ' 的 <strong>'
                + currentAlertInfo.itemName + '</strong> 当前值为 <span style="color:#FFB800;">' + currentAlertInfo.currentValue
                + '</span> ,请关注!',
                autoClose:true,
                time:5000
            });
            window.alertIndex++;

        }
        /*************************************************************************后台任务*******************************************************************/
        /************************************************************************服务器操作***************************************************************/
        //删除
        function serverDel(obj, callback, notShowTip) {
            var serverType = $(obj).attr('server-type'), viewId = $(obj).attr('data-id');
            $.post(serverInfos[serverType]['namespace'] + MONITORING_SERVER_DEL_URL,
                    {userKey:userKey, serverType:serverType, viewId:viewId},
                    function(json) {
                        typeof callback == 'function' && callback(json);
                        notShowTip || validatReturnJson(json, function(){
                            //清除缓存
                            delData(serverType, viewId);
                            //立即删除指定表格行
                            viewInstances[serverType]["table"].row($(obj).parents('tr')).remove().draw();
                            layer.msg('删除成功!', {icon:1, time:1600});
                        });

                    });
        }

        //重连
        function serverReconnect(obj, callback, notShowTip) {
            var serverType = $(obj).attr('server-type'), viewId = $(obj).attr('data-id');
            $.post(serverInfos[serverType]['namespace'] + MONITORING_SERVER_RECONNECT_URL,
                    {userKey:userKey, serverType:serverType, viewId:viewId}, function(json){
                        typeof callback == 'function' && callback(json);
                        notShowTip || validatReturnJson(json, function(){
                            layer.msg('重新连接成功,请刷新表格查看最新状态!', {icon:1, time:1600});
                        });
                    });
        }

        /*************************************************************************服务器操作**************************************************************/

        /**
         *
         * 删除表格：清除指定表格的所有信息
         * @param serverType 保存指定类型 可传入数组,传入all删除全部
         * @param callback 获取路径供下载
         */
        function delTableData(serverType, callback) {
        	var typeArr = [];
            if (serverType == 'all') {
                $.each(serverInfos.viewTypes, function(type, name) {
                    typeArr.push(type);
                });
            } else {
                typeArr = rmputils.arrayUtils.isArray(serverType) ? serverType : [serverType];
            }
            
            $.each(typeArr, function(i, n) {
            	$.post(serverInfos[n]['namespace'] + MONITORING_SERVER_DEL_ALL_URL, {userKey:userKey, serverType:n}, function(json){  
            		callback(json, n);
            	});
            });  
        }
        /**
         *
         * 保存数据:发送当前数据到服务器，生成离线数据文件供下载
         * @param serverType 保存指定类型 可传入数组
         * @param callback 获取路径供下载
         */
        function saveData(serverType, callback) {
            var typeArr = [];
            if (serverType == 'all') {
                $.each(serverInfos.viewTypes, function(type, name) {
                    typeArr.push(type);
                });
            } else {
                typeArr = rmputils.arrayUtils.isArray(serverType) ? serverType : [serverType];
            }

            var sendData = {
                userKey:userKey
            };
            var infoDataT = {};
            var serverList = {};
            sendData.serverCount = 0;
            sendData.infoCount = 0;
            $.each(typeArr, function(i, type) {
                infoDataT[type] = infoData[type];
                serverList[type] = [];
                $.each(infoData[type], function(viewId, info){
                    serverList[type].push({
                        viewId:viewId,
                        startTime:info.time[0],
                        lastTime:info.time[info.time.length - 1],
                        count:info.time.length
                    });
                    sendData.infoCount += info.time.length;
                    sendData.serverCount ++;
                });

            });
            sendData.infoData = JSON.stringify(infoDataT);
            sendData.serverList = JSON.stringify(serverList);
            
            layer.prompt({
            	  formType: 0,
            	  value: '这是备注',
            	  title: '输入保存文件备注信息',
            	  area: ['400px', '100px'] //自定义文本域宽高
            	}, function(value, index, elem){
            		sendData.mark = value;
            		globalLoadIndex = layer.msg('正在保存数据...', {icon:16, time:9999999, shade:0.4});
            		$.post(MONITORING_SERVER_SAVE_DATA_URL, sendData, function(json){
            			layer.close(globalLoadIndex);
                        typeof callback == 'function' && callback(json);
                    });
            	  layer.close(index);
            	});                      
        }



        /**
         *
         *
         * 删除当前缓存中的数据 如果serverType传入all 则删除全部
         * @param serverType 服务器类型
         * @param viewId 指定的viewId 可传入数组
         *
         */
        function delData(serverType, viewId) {
            //全部
            if (serverType == 'all') {
                infoData = {};
                infoCount = 0;
                return;
            }

            //指定类型
            if (serverType != undefined && viewId == undefined) {
                $.each(infoData[serverType], function(i, n){
                    infoCount -= n.time.length;
                });
                delete infoData[serverType];
                return;
            }

            //指定类型下的指定服务器
            if (serverType != undefined && viewId != undefined) {
                var idArr = rmputils.arrayUtils.isArray(viewId) ? viewId : [viewId];

                $.each(idArr, function(i, id){
                    infoCount -= (infoData[serverType][id]['time']).length;
                    infoData[serverType][id] != undefined && (delete infoData[serverType][id]);
                });

                return;
            }
        }


        /**
         * 获取一些本地缓存的一些数据并设置到当前空间中
         */
        function initLocalSetting () {
            //获取视图显示设置
            var viewVisible = getLocalData('viewVisible', true);
            viewVisible == null && (viewVisible = {});
            $.each(serverInfos.viewTypes, function(type, name) {
                viewVisibleSetting[type] = typeof viewVisible[type] == 'boolean' ? viewVisible[type] : false;
                if (viewVisibleSetting[type]) {
                    $("#" + type).show();
                } else {
                    $("#" + type).hide();
                }
            });

            //获取缓存的监控数据
            (infoData = getLocalData('infoData', true, true)) == null && (infoData = {});

            //获取本地计数器
            (infoCount = getLocalData('infoCount', false, true)) == null && (infoCount = 0);
        }

        /**
         * 在关闭或者刷新页面保存数据到本地存储中
         */
        function saveLocalSetting() {
            saveLocalData('viewVisible', viewVisibleSetting);
            saveLocalData('infoData', infoData, true);
            saveLocalData('infoCount', infoCount, true);
        }
    });


</script>
</body>

</html>

